package cn.smbms.controller.user;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.role.RoleServiceImpl;
import cn.smbms.service.user.UserService;
import cn.smbms.service.user.UserServiceImpl;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController{

    @Autowired
    private UserService userService;
    @Resource
    private RoleService roleService;
    @RequestMapping("/login")
    public String login(String userCode, String userPassword, HttpSession session, HttpServletRequest request){
        System.out.println("login ============ " );
        //调用service方法，进行用户匹配
        User user = userService.login(userCode,userPassword);
        if(null == user){
          throw new RuntimeException("用户名或密码错误");
        }
        session.setAttribute(Constants.USER_SESSION,user);
        //重定向
        return "redirect:/user/sys/main";
    }
    @RequestMapping("/sys/main")
    public String main(){
        return "frame";
    }


    /*@ExceptionHandler(value={RuntimeException.class})
    public String handleException(RuntimeException e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "error";
    }*/
    /*查询用户列表*/
    @RequestMapping("/list")
    public String userlist(String queryname,String queryUserRole,String pageIndex,HttpServletRequest request){
        //查询用户列表
        /*String queryUserName = request.getParameter("queryname");
        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");*/
        int _queryUserRole = 0;
        //UserService userService = new UserServiceImpl();
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        /**
         * http://localhost:8090/SMBMS/userlist.do
         * ----queryUserName --NULL
         * http://localhost:8090/SMBMS/userlist.do?queryname=
         * --queryUserName ---""
         */
        System.out.println("queryUserName servlet--------"+queryname);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
        if(queryname == null){
            queryname = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/user/syserror";
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryname,_queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }


        userList = userService.getUserList(queryname,_queryUserRole,currentPageNo, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;
        //RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        request.setAttribute("roleList", roleList);
        request.setAttribute("queryUserName", queryname);
        request.setAttribute("queryUserRole", _queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);
       return "/userlist";
    }
    @RequestMapping("/syserror")
    public String syserror(){
        return "error";
    }

    @RequestMapping(value="/useradd",method = RequestMethod.GET)
    public String toUserAdd(@ModelAttribute("user")User user){
        return "useradd";
    }

    @RequestMapping(value="/useradd",method = RequestMethod.POST)
    public String useradd(User user, HttpSession session,HttpServletRequest request,
                          @RequestParam(value="attaches",required = false) MultipartFile[] multipartFiles){

        System.out.println("进入添加。。。。。。。。。。。。。。。");
        String idPicPath=null;
        String workPicPath=null;
        String erroInfo=null;
        //准备工作：1、定义上传的目标路径。
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"upload");
        for (int i = 0; i < multipartFiles.length; i++) {
            MultipartFile multipartFile=multipartFiles[i];
            if(!multipartFile.isEmpty()){
                if(i==0){
                    erroInfo="uploadFileError";
                }else if(i==2){
                    erroInfo="uploadWpError";
                }
                //2、获取原文件名
                String oldFileName=multipartFile.getOriginalFilename();
                //3、获取源文件的后缀
                String suffix= FilenameUtils.getExtension(oldFileName);
                //4、获取源文件大小
                long size=multipartFile.getSize();
                if(size>500000){
                    request.setAttribute(erroInfo,"上传文件大小不能超过500KB");
                    return "useradd";
                }else if(suffix.equalsIgnoreCase("jpg")
                        ||suffix.equalsIgnoreCase("png")
                        ||suffix.equalsIgnoreCase("jpeg")
                        ||suffix.equalsIgnoreCase("pneg")){
                    //定义上传的文件名
                    String newFileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"."+suffix;
                    //把即将上传的文件定义
                    File targetFile=new File(path,newFileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }

                    try {
                        //写入，上传，保存
                        multipartFile.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(erroInfo,"上传失败");
                        return "useradd";
                    }
                    if(i==0){
                        idPicPath=newFileName;
                    }else if(i==1){
                        workPicPath=newFileName;
                    }

                }else{
                    request.setAttribute(erroInfo,"文件的格式不正确");
                    return "useradd";
                }
            }
        }

        user.setIdPicPath(idPicPath);
        user.setWorkPicPath(workPicPath);
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)(session.getAttribute(Constants.USER_SESSION))).getId());
        if(userService.add(user)){
            return "redirect:/user/list";
        }
        return "useradd";

    }

    /**
     * 预修改，根据id查询user对象，传到修改页面
     * @param uid
     * @param model
     * @return
     */
    @RequestMapping("/tomodity")
    public String tomodity(String uid, Model model){
        User user=userService.getUserById(uid);
        model.addAttribute("user",user);
        return "usermodify";

    }

    /**
     * 真正修改方法
     * @return
     */
    @RequestMapping("/usermodify")
    public String usermodify(User user,HttpSession session){
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if(userService.modify(user)){
            return "redirect:/user/list";
        }
        return "usermodify";
    }

    /**
     * 查询用户详情
     * @return
     */
    @RequestMapping(value="/userView/{id}",method = RequestMethod.GET)
    public String userView(@PathVariable String id,Model model){
        User user=userService.getUserById(id);
        model.addAttribute("user",user);
        return "userview";
    }

    /**
     * 异步处理方法，验证用户编码唯一
     * @param userCode
     * @return
     */
    @RequestMapping("/ucexist")
    @ResponseBody
    public  Object ucexist(String userCode){
        HashMap<String,String> resultMap=new HashMap<String,String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode","exist");
        }else{
           User user= userService.selectUserCodeExist(userCode);
           if(null!=user){
               resultMap.put("userCode","exist");
           }else{
               resultMap.put("userCode","noexist");
           }
        }
        return JSONArray.toJSONString(resultMap);
    }
    @RequestMapping(value="/view",method = RequestMethod.GET)
    @ResponseBody
    public User view(String id){
        User user=null;
            try{
                user=userService.getUserById(id);
            }catch (Exception e){
                e.printStackTrace();
            }
        return  user;
    }

    /**
     * 处理微信请求的处理方法
     * @param param
     * @return
     */
    @RequestMapping("/wxlist")
    @ResponseBody
    public  List<User> getUserList(Integer param){
        System.out.println(param);
        List<User> userList=new ArrayList<User>();
        User user=new User();
        user.setUserCode("admin");
        user.setUserName("张三");
        user.setBirthday(new Date());
        userList.add(user);
        User user1=new User();
        user1.setUserCode("aaa");
        user1.setUserName("李四");
        user1.setBirthday(new Date());
        userList.add(user1);
        User user2=new User();
        user2.setUserCode("bbb");
        user2.setUserName("王五");
        user2.setBirthday(new Date());
        userList.add(user2);
        User user3=new User();
        user3.setUserCode("ccc");
        user3.setUserName("兆良");
        user3.setBirthday(new Date());
        userList.add(user3);
        return  userList;
    }


}
